<template>
  <div class="observer-target" ref="targetEl"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const emit = defineEmits(['intersect'])

const targetEl = ref(null); // 观察的目标元素
let observer = null;

onMounted(() => {
  const options = {
    root: null,
    rootMargin: '0px',
    threshold: 0.1,
  };

  observer = new IntersectionObserver(([entry]) => {
    if (entry && entry.isIntersecting) {
      emit('intersect'); // 交互通知
    }
  }, options);

  observer.observe(targetEl.value);
});

onBeforeUnmount(() => {
  observer?.disconnect(); // 组件卸载时停止观察
});
</script>

<style scoped>
.observer-target {
  width: 100%;
  height: 10px;
  background: transparent;
}
</style>